﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace HousingDistribution
{
    public partial class FormHousingSelect : Form
    {
        public FormHousingSelect(PersonInfo curPerInfo, FormPersonDetailsNoHousingTab.UpdatePersonHousingInfoDelegate updateFunc)
        {
            InitializeComponent();
            InitDGVSelectHousing();

            //处理界面布局
            this.dataGridViewSelectHousing.Dock = DockStyle.Fill;
            this.dataGridViewSelectHousing.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom;
            this.labelStreetNo.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            this.checkBox27.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            this.checkBox38.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            this.checkBox48.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            this.buttonSelectHouse.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            this.labelHousingType.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            this.comboBoxHouseType.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            this.labelBuildingNo.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            this.comboBoxBuildingNo.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            this.labelDoorway.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            this.comboBoxDoorWay.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            this.buttonHousingDis.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            this.buttonClose.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;

            this.Dock = DockStyle.Fill;

            this.curPerInfo = curPerInfo;
            this.updateFunc = updateFunc;
            //备份住房信息
            if (curPerInfo.housingInfo != null && curPerInfo.housingInfo.Count > 0)
                this.orginalHousingInfo = new List<HousingOccupancyInfo>(curPerInfo.housingInfo);
        }

        private void FormHousingSelect_Load(object sender, EventArgs e)
        {
            DoAsynQuery asynQuery = new DoAsynQuery(this, ref this.curPerInfo, true, null, null, null, null);
            Thread queryThread = new Thread(asynQuery.Do);
            queryThread.Start();
        }

        private void InitDGVSelectHousing()
        {
            DGVInit.Init(ref this.dataGridViewSelectHousing, DataDictionary.Instance().GetDGVConf(DataDictionary.Instance().dgvNames[2]));
        }

        //人员发生变化时，需调用该函数完成分房状态区域的刷新
        private void RefreshHousingDisState(PersonInfo personInfo)
        {
            if (personInfo.housingEligible == 1)
            {
                EnableHousingDis(true);
                AsynQueryHousingInfo();
            }
            else
            {
                EnableHousingDis(false);
            }
        }

        private void EnableHousingDis(bool enabled)
        {
            this.dataGridViewSelectHousing.Enabled = enabled;
            this.checkBox27.Enabled = enabled;
            this.checkBox38.Enabled = enabled;
            this.checkBox48.Enabled = enabled;
            this.comboBoxHouseType.Enabled = enabled;
            this.comboBoxBuildingNo.Enabled = enabled;
            this.comboBoxDoorWay.Enabled = enabled;
            this.buttonSelectHouse.Enabled = enabled;
            this.buttonHousingDis.Enabled = enabled;
        }

        public void AsynQueryHousingInfo()
        {
            string[] streetNo = new string[3];

            int index = 0;

            if (checkBox27.Checked)
            {
                streetNo[index] = "27";
                index++;
            }
            if (checkBox38.Checked)
            {
                streetNo[index] = "38";
                index++;
            }
            if (checkBox48.Checked)
            {
                streetNo[index] = "48";
                index++;
            }

            string housingType = null;
            if (this.comboBoxHouseType.SelectedItem != null && this.comboBoxHouseType.Text.Length > 0)
            {
                housingType = this.comboBoxHouseType.Text;
            }

            string buildingNo = null;
            if (this.comboBoxBuildingNo.SelectedItem != null && this.comboBoxBuildingNo.Text.Length > 0)
            {
                buildingNo = this.comboBoxBuildingNo.Text;
            }

            string doorWay = null;
            if (this.comboBoxDoorWay.SelectedItem != null && this.comboBoxDoorWay.Text.Length > 0)
            {
                doorWay = this.comboBoxDoorWay.Text;
            }

            DoAsynQuery asynQuery = new DoAsynQuery(this, ref this.curPerInfo, false, streetNo, housingType, buildingNo, doorWay);
            Thread queryThread = new Thread(asynQuery.Do);
            queryThread.Start();
        }

        private class DoAsynQuery
        {
            public DoAsynQuery(FormHousingSelect parent, ref PersonInfo personInfo, bool onlyQueryCurHousing, string[] streetNo, string housingType, string buildingNo, string doorWay)
            {
                this.parent = parent;
                this.personInfo = personInfo;
                this.streetNo = streetNo;
                this.housingType = housingType;
                this.buildingNo = buildingNo;
                this.doorWay = doorWay;

                this.onlyQueryCurHousing = onlyQueryCurHousing;
            }
            public void Do()
            {
                HousingQuery housingQuery = new HousingQuery();

                try
                {
                    DataTable dt = null;

                    if (this.onlyQueryCurHousing)
                        dt = housingQuery.Read(personInfo);
                    else
                        dt = housingQuery.Read(personInfo, streetNo, housingType, buildingNo, doorWay);

                    BindData(dt);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "查询房屋数据错误");
                }
            }

            void BindData(DataTable dt)
            {
                if (parent.dataGridViewSelectHousing.InvokeRequired)
                {
                    BindDataDelegate d = new BindDataDelegate(BindData);
                    parent.Invoke(d, new object[] { dt });
                }
                else
                {
                    parent.dataGridViewSelectHousing.DataSource = dt;
                }
            }

            private delegate void BindDataDelegate(DataTable dt);

            FormHousingSelect parent;
            PersonInfo personInfo;
            string[] streetNo;
            string housingType, buildingNo, doorWay;

            bool onlyQueryCurHousing;
        }

        private void QueryHousingInfo()
        {
            string[] streetNo = new string[3];

            int index = 0;

            if (checkBox27.Checked)
            {
                streetNo[index] = "27";
                index++;
            }
            if (checkBox38.Checked)
            {
                streetNo[index] = "38";
                index++;
            }
            if (checkBox48.Checked)
            {
                streetNo[index] = "48";
                index++;
            }

            string housingType = null;
            if (this.comboBoxHouseType.SelectedItem != null && this.comboBoxHouseType.Text.Length > 0)
            {
                housingType = this.comboBoxHouseType.Text;
            }

            string buildingNo = null;
            if (this.comboBoxBuildingNo.SelectedItem != null && this.comboBoxBuildingNo.Text.Length > 0)
            {
                buildingNo = this.comboBoxBuildingNo.Text;
            }

            string doorWay = null;
            if (this.comboBoxDoorWay.SelectedItem != null && this.comboBoxDoorWay.Text.Length > 0)
            {
                doorWay = this.comboBoxDoorWay.Text;
            }

            HousingQuery housingQuery = new HousingQuery();

            try
            {
                DataTable dt = housingQuery.Read(this.curPerInfo, streetNo, housingType, buildingNo, doorWay);

                this.dataGridViewSelectHousing.DataSource = dt;

                this.buttonHousingDis.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "查询房屋数据错误");
            }
        }

        private void dataGridViewSelectHousing_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int rowIndex = e.RowIndex;
            int colIndex = e.ColumnIndex;

            if (rowIndex < 0 || colIndex < 0)
                return;

            DataGridViewRow dr = this.dataGridViewSelectHousing.Rows[rowIndex];
            string colName = this.dataGridViewSelectHousing.Columns[colIndex].Name;

            List<HousingOccupancyInfo> housingInfo = this.curPerInfo.housingInfo;

            //不是“选房资格”的item则忽略
            if (housingInfo != null && colName.Equals(DataDictionary.Instance().DGVNewColName(DGVNewColConsts.SELECT)))
            {
                int housingID = Convert.ToInt16(dr.Cells[DataDictionary.Instance().HousingTableFieldName(HousingColConsts.ID)].FormattedValue);

                bool isChecked = Convert.ToBoolean(dr.Cells[DataDictionary.Instance().DGVNewColName(DGVNewColConsts.SELECT)].EditedFormattedValue);

                //如果选中，则获取对应的房子id
                if (isChecked)
                {
                    //当前住房列表不存在该记录，则增加
                    if (this.housingInfoProc.HousingIsCurOccupancy(housingID, housingInfo) == false)
                    {
                        HousingOccupancyInfo info = new HousingOccupancyInfo();
                        info.id = housingID;
                        info.checkinTime = System.DateTime.Now;

                        housingInfo.Add(info);
                    }
                }
                else
                {
                    //当前住房列表存在该记录，删除
                    foreach (HousingOccupancyInfo info in housingInfo)
                    {
                        if (info.id == housingID)
                        {
                            housingInfo.Remove(info);
                            break;
                        }
                    }

                }
            }
        }

        private void checkBox27_CheckedChanged(object sender, EventArgs e)
        {
            CtrlHousingComoboxState();
            ProcBuildingNo_DoorwayCombox();
        }

        private void checkBox38_CheckedChanged(object sender, EventArgs e)
        {
            CtrlHousingComoboxState();
            ProcBuildingNo_DoorwayCombox();
        }

        private void checkBox48_CheckedChanged(object sender, EventArgs e)
        {
            CtrlHousingComoboxState();
            ProcBuildingNo_DoorwayCombox();
        }

        //控制分房选择的ComboBox，当且仅当只有一个checkbox的时候激活comboBox，其他情况均disable
        private void CtrlHousingComoboxState()
        {
            if ((checkBox27.Checked && !checkBox38.Checked && !checkBox48.Checked)
                || (!checkBox27.Checked && checkBox38.Checked && !checkBox48.Checked)
                || (!checkBox27.Checked && !checkBox38.Checked && checkBox48.Checked))
            {
                this.comboBoxBuildingNo.Enabled = true;
                this.comboBoxDoorWay.Enabled = true;
            }
            else
            {
                this.comboBoxBuildingNo.Enabled = false;
                this.comboBoxDoorWay.Enabled = false;
            }
        }

        private void comboBoxHouseType_SelectedIndexChanged(object sender, EventArgs e)
        {
            AsynQueryHousingInfo();
        }
        //楼号的选择发生变化时，需根据楼号动态生成楼道ComboBox
        private void comboBoxBuildingNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.comboBoxBuildingNo.SelectedItem != null && this.comboBoxBuildingNo.Text.Length > 0)
                {
                    string buildingNo = this.comboBoxBuildingNo.Text;

                    string streetNo = GetStreetNo();
                    if (streetNo != null)
                        CreateDoorwayComboxItem(this.comboBoxDoorWay, streetNo, buildingNo);

                    AsynQueryHousingInfo();
                }
            }
            catch (Exception)
            {
            }
        }

        private void comboBoxDoorWay_SelectedIndexChanged(object sender, EventArgs e)
        {
            AsynQueryHousingInfo();
        }

        private void ProcBuildingNo_DoorwayCombox()
        {
            string streetNo = GetStreetNo();

            if (streetNo != null)
            {
                CreateHousingTypeComboxItem(this.comboBoxHouseType, streetNo);
                CreateBuildingNoComboxItem(this.comboBoxBuildingNo, streetNo);
            }
        }

        private string GetStreetNo()
        {
            string streetNo = null;

            if (checkBox27.Checked && !checkBox38.Checked && !checkBox48.Checked)
            {
                streetNo = "27";
            }
            else if (!checkBox27.Checked && checkBox38.Checked && !checkBox48.Checked)
            {
                streetNo = "38";
            }
            if (!checkBox27.Checked && !checkBox38.Checked && checkBox48.Checked)
            {
                streetNo = "48";
            }
            else
            {
            }

            return streetNo;
        }

        private void CreateHousingTypeComboxItem(ComboBox cb, string streetNo)
        {
            List<string> housingType = DataDictionary.Instance().HousingTypeTableInMySql(streetNo);
            if (housingType == null)
                return;

            cb.Items.Clear();
            cb.Items.Add("");
            foreach (string type in housingType)
            {
                cb.Items.Add(type);
            }
        }

        private void CreateBuildingNoComboxItem(ComboBox cb, string streetNo)
        {
            string[] buildingNo = DataDictionary.Instance().BuildingNoTableInMySql(streetNo);

            if (buildingNo == null)
                return;
            
            cb.Items.Clear();
            cb.Items.Add("");

            foreach (string no in buildingNo)
            {
                cb.Items.Add(no);
            }
        }

        private void CreateDoorwayComboxItem(ComboBox cb, string streetNo, string buildingNo)
        {
            List<string> doorway = DataDictionary.Instance().DoorwayTableInMySql(streetNo, buildingNo);

            if (doorway == null)
                return;
            
            cb.Items.Clear();
            cb.Items.Add("");

            foreach (string no in doorway)
            {
                cb.Items.Add(no);
            }
        }

        //界面控件事件响应处理函数
        private void buttonSelectHouse_Click(object sender, EventArgs e)
        {
            AsynQueryHousingInfo();
        }

        //根据给定id判断是不是当前住房
        private bool IsCurHousing(int idhousing, List<HousingOccupancyInfo> curHousing)
        {
            if (curHousing == null)
                return false;

            foreach (HousingOccupancyInfo info in curHousing)
            {
                if (info.id == idhousing)
                    return true;
            }
            return false;
        }
        private void buttonHousingDis_Click(object sender, EventArgs e)
        {
            //根据当前住房信息和上次住房信息来确定历史住房信息
            if (this.orginalHousingInfo != null && this.orginalHousingInfo.Count > 0)
            {
                List<int> formerHousingId = new List<int>();

                foreach (HousingOccupancyInfo info in this.orginalHousingInfo)
                {   
                    if (IsCurHousing(info.id, this.curPerInfo.housingInfo) == false)
                        formerHousingId.Add(info.id);
                }

                if (formerHousingId.Count > 0)
                    this.curPerInfo.formerHousingId = formerHousingId;
            }
            else
                this.curPerInfo.formerHousingId.Clear();

            //根据最新住房信息更新数据库
            string sql = this.sqlCreator.UpdateOnlyForHousingInfo(this.curPerInfo);

            try
            {
                DBProc.Instance().Excute(sql);

                //通过回调函数处理父窗口住房信息的界面刷新
                updateFunc(this.curPerInfo);

                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "更新人员住房信息");
            }
        }
        private void buttonClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //人员信息
        private PersonInfo curPerInfo;
        //该人员的住房信息（在窗口创建的时候复制人员的住房信息，在退出的时候通过对比住房信息，来确定历史住房）
        private List<HousingOccupancyInfo> orginalHousingInfo = null;
        
        HousingInfoProc housingInfoProc = new HousingInfoProc();
        DataStruct2SQL sqlCreator = new DataStruct2SQL();

        FormPersonDetailsNoHousingTab.UpdatePersonHousingInfoDelegate updateFunc;
    }
}
